package com.st.lotte.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.TimeUnit;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.write.WritableWorkbook;

import org.apache.poi.ss.formula.functions.Count;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.st.lotte.dao.LateDAO;
import com.st.lotte.dao.CodeDAO;
import com.st.lotte.dao.DelyStatCodeDAO;
import com.st.lotte.dao.TLO_DELY_TRCE_RECV_IF_DAO;
import com.st.lotte.model.Code;
import com.st.lotte.model.TLO_DELY_TRCE_RECV_IF;
import com.st.lotte.page.PagingBean;
import com.st.lotte.page.PagingUtil;
import com.st.lotte.view.AbstractPOIExcelView;
import com.st.lotte.view.DownloadView;
import com.st.lotte.view.SimpleExcellView;

public class TestController extends HttpServlet{
	Logger log = LoggerFactory.getLogger(TestController.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req,resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req,resp);
	}
	
	public String alert(String msg){
		String str ="<script>";
		str+="alert('"+msg+"'); ";
		str+="</script>";
		return str;
	}
	
	public void forward(HttpServletRequest req, HttpServletResponse resp, String url){
		try {
			RequestDispatcher dispatcher = req.getRequestDispatcher(url);
			dispatcher.forward(req,resp);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) {
		log.debug("[testcontroller]- start!!");
		TLO_DELY_TRCE_RECV_IF_DAO dao = new TLO_DELY_TRCE_RECV_IF_DAO();
		CodeDAO cDao = new CodeDAO();
		DelyStatCodeDAO delyDao = new DelyStatCodeDAO();
		LateDAO calDao = new LateDAO();
		
		HttpSession session = req.getSession();
		
		try {
			req.setCharacterEncoding("euc-kr");
			resp.setContentType("text/html; charset=euc-kr");
			PrintWriter out = resp.getWriter();
			String command = req.getParameter("command");
			
			// login 처리
			System.out.println("command---"+command);
			if (command.equalsIgnoreCase("login")) {
				log.debug("[controller - login ]- start!!");
				String username = req.getParameter("username");
				String password = req.getParameter("password");
				if (username.equals("admin") && password.equals("lotte!23")) {
					session.setAttribute("loginID", username);
					forward(req, resp, "main.jsp");
				}else{
					out.print(alert("아이디와 패스워드가 정확하지 않습니다."));
				}
				log.debug("[controller - login ]- end!!");
				
			// log out 처리
			}else if(command.equalsIgnoreCase("logout")){
				log.debug("[controller - logout ]- start!!");
				out.print(alert("로그 아웃되었습니다."));
				session.invalidate();
				forward(req, resp, "login.jsp");
				log.debug("[controller - logout ]- end!!");
				
			// 발송지연처리 - login 처리하고 나서 첫화면
			}else if(command.equalsIgnoreCase("late")){
				log.debug("[controller - latesearch.jsp ]- start!!");
				String str = "";
				
				log.debug("[testcontroller - latesearch paging ]- start ! ");
				// paging 처리
				PagingBean paging = new PagingBean();
				if(req.getParameter("nowPage") == null){
					 paging.setNowPage(1);
				}else{
					 paging.setNowPage(Integer.valueOf(req.getParameter("nowPage")));
				}
				log.debug("[testcontroller - latesearch paging ]- end ! ");
				
				// 데이터 전체 카운트 
		        int count = dao.selectNotDeliveryDataCNT();
		        // limit로 가져오는 개수 처리하기 위한 변수
				int pgCount = paging.getNowPage()==1?1:paging.getNowPage()*paging.getCountPerPage();
		        
				//  현재날짜를 가져와서 한달전의 데이터를 가져온다.
				SimpleDateFormat formatter1 = new SimpleDateFormat ("yyyy-MM-dd");
		        String date = formatter1.format(new Date());
				
//		        str+=String.format(" limit ?,?",pgCount,pgCount+paging.getCountPerPage()); // 30건만 먼저 불러오기 위한 limit 
		        
				str = String.format(" and RECV_DATE>=('%s' - INTERVAL 1 MONTH) limit %d,%d ",date,pgCount,pgCount+paging.getCountPerPage()); 
				log.debug("[controller - latesearch.jsp ]- 1! ");
				
				Vector<TLO_DELY_TRCE_RECV_IF> list = dao.selectNotDeliveryData(str,"");
				Vector<Code> codeList = cDao.getCodeLists();
				Vector<Code> delySataList = delyDao.getCodeLists();
				log.debug("[testcontroller - latesearch.jsp ]- 4! "+delySataList);
				
				req.setAttribute("count", count);
				req.setAttribute("paging", paging);
				req.setAttribute("delyStatList", delySataList);
				req.setAttribute("codeList", codeList);
				req.setAttribute("recvDTOList", list);
				forward(req, resp, "latesearch.jsp");
				log.debug("[controller - latesearch.jsp ]- end!!");

			// 전체송장 대상 검색
			}else if(command.equalsIgnoreCase("search_argument")){
				log.debug("[testcontroller - search_result.jsp ]- search_argument start! ");
				log.debug("[testcontroller - search_result.jsp ]- 1---"+req.getParameter("hodeco_code")+" 2"+req.getParameter("slip_no")+" 3"+req.getParameter("cmbn_ord_no")+" 4"+req.getParameter("ord_sDate")+" 5"+req.getParameter("ord_eDate")+" 6"+req.getParameter("reg_sDate"));
				
				String str = "";
				// 검색조건 - 택배사 코드 
				if (req.getParameter("hodeco_code")==null || req.getParameter("hodeco_code").equalsIgnoreCase("") || req.getParameter("hodeco_code").equalsIgnoreCase("all")) {
				}else{
					str +=  String.format(" and HODECO_CODE='%s' ",req.getParameter("hodeco_code"));
				}
				
				// 검색조건 - 운송장번호 
				if (req.getParameter("slip_no")==null || req.getParameter("slip_no").equalsIgnoreCase("")) {
				}else{
					str += String.format(" and SLIP_NO='%s' ",req.getParameter("slip_no"));
				}
				
				// 검색조건 - 주문번호
				if (req.getParameter("cmbn_ord_no")==null || req.getParameter("cmbn_ord_no").equalsIgnoreCase("")) {
				}else{
					str += String.format(" and CMBN_ORD_NO='%s' ",req.getParameter("cmbn_ord_no"));
				}
				
				// 검색조건 - 택배사처리일자
				if (req.getParameter("ord_sDate")==null || req.getParameter("ord_eDate").equalsIgnoreCase("")) {
				}else{
					str += String.format(" and TRCE_STAT_PROC_DT>='%s' and TRCE_STAT_PROC_DT<='%s' ",req.getParameter("ord_sDate"),req.getParameter("ord_eDate"));
				}
				
				// 검색조건 - 롯데기준 수신일자
				if (req.getParameter("reg_sDate")==null || req.getParameter("reg_eDate").equalsIgnoreCase("")) {
				}else{
					str += String.format(" and RECV_DATE>='%s' and RECV_DATE<='%s' ", req.getParameter("reg_sDate") , req.getParameter("reg_eDate"));
				}
				
				// 검색조건이 없을때 현재날짜를 가져와서 한달전의 데이터를 가져온다.
				SimpleDateFormat formatter1 = new SimpleDateFormat ("yyyy-MM-dd");
		        String date = formatter1.format(new Date());
				
				// 검색조건이 아무것도 없을 경우 
				if (str==null || str.equals("")) {
					str = String.format(" and RECV_DATE=('%s' - INTERVAL 1 MONTH) ",date);
				}
				
				str += " limit 30 ";
				
				// paging 처리
				PagingBean paging = new PagingBean();
				if(req.getParameter("nowPage") == null){
					 paging.setNowPage(1);
				}else{
					 paging.setNowPage(Integer.valueOf(req.getParameter("nowPage")));
				}
				
				// 전체송장 대상
				Vector<TLO_DELY_TRCE_RECV_IF> list = dao.selectALLRecvData(str,"");
				Vector<Code> codeList = cDao.getCodeLists();
				Vector<Code> delySataList = delyDao.getCodeLists();
				log.debug("[testcontroller - search_result.jsp ]- 5! "+delySataList);
				
				req.setAttribute("paging", paging);
				req.setAttribute("delyStatList", delySataList);
				req.setAttribute("codeList", codeList);
				req.setAttribute("recvDTOList", list);
				forward(req, resp, "search_result.jsp");
				log.debug("[testcontroller - search_result.jsp ]- end!!");					
				
			// 미배송 관리
			}else if(command.equalsIgnoreCase("latesearch")){
				log.debug("[testcontroller - latesearch.jsp ]- latesearch start! ");
				log.debug("[testcontroller - latesearch.jsp ]- 1---"+req.getParameter("hodeco_code")+" 2"+req.getParameter("slip_no")+" 3"+req.getParameter("cmbn_ord_no")+" 4"+req.getParameter("ord_sDate")+" 5"+req.getParameter("ord_eDate")+" 6"+req.getParameter("reg_sDate"));
				
				// 데이터 전체 카운트 
		        int count = dao.selectNotDeliveryDataCNT();
		        
		        // paging 처리 - start 
				PagingBean paging = new PagingBean();
				if(req.getParameter("nowPage") == null){
					 paging.setNowPage(1);
				}else{
					 paging.setNowPage(Integer.valueOf(req.getParameter("nowPage")));
				}
				PagingUtil.setPagingInfo(paging);
				// paging 처리 - end
		        
				// limit로 가져오는 개수 처리하기 위한 변수
				int pgCount = paging.getNowPage()==1?1:paging.getNowPage()*paging.getCountPerPage();
				
				String str = "";
				// 검색조건 - 택배사 코드 
				if (req.getParameter("hodeco_code")==null || req.getParameter("hodeco_code").equalsIgnoreCase("") || req.getParameter("hodeco_code").equalsIgnoreCase("all")) {
				}else{
					str +=  String.format(" and HODECO_CODE='%s' ",req.getParameter("hodeco_code"));
				}
				
				// 검색조건 - 운송장번호 
				if (req.getParameter("slip_no")==null || req.getParameter("slip_no").equalsIgnoreCase("")) {
				}else{
					str += String.format(" and SLIP_NO='%s' ",req.getParameter("slip_no"));
				}
				
				// 검색조건 - 주문번호
				if (req.getParameter("cmbn_ord_no")==null || req.getParameter("cmbn_ord_no").equalsIgnoreCase("")) {
				}else{
					str += String.format(" and CMBN_ORD_NO='%s' ",req.getParameter("cmbn_ord_no"));
				}
				
				// 검색조건 - 택배사처리일자
				if (req.getParameter("ord_sDate")==null || req.getParameter("ord_eDate").equalsIgnoreCase("")) {
				}else{
					str += String.format(" and TRCE_STAT_PROC_DT>='%s' and TRCE_STAT_PROC_DT<='%s' ",req.getParameter("ord_sDate"),req.getParameter("ord_eDate"));
				}
				
				// 검색조건 - 롯데기준 수신일자
				if (req.getParameter("reg_sDate")==null || req.getParameter("reg_eDate").equalsIgnoreCase("")) {
				}else{
					str += String.format(" and RECV_DATE>='%s' and RECV_DATE<='%s' ", req.getParameter("reg_sDate") , req.getParameter("reg_eDate"));
				}
				
				// 검색조건 - 배송상태값 
				if (req.getParameter("trce_stat_code")==null || req.getParameter("trce_stat_code").equalsIgnoreCase("")) {
				}else{
					str += String.format(" and TRCE_STAT_CODE>='%s' ", req.getParameter("trce_stat_code"));
				}
				
				// 검색조건이 아무것도 없을 경우 
				if (str==null || str.equals("")) {
					str = "and RECV_DATE>='2014-11-10' and RECV_DATE<='2014-11-11' ";
				}
				
				str+=String.format(" limit ?,?",pgCount,pgCount+paging.getCountPerPage()); // 30건만 먼저 불러오기 위한 limit 
				
				Vector<TLO_DELY_TRCE_RECV_IF> list = dao.selectNotDeliveryData(str,"");
				Vector<Code> codeList = cDao.getCodeLists();
				Vector<Code> delySataList = delyDao.getCodeLists();
				log.debug("[testcontroller - latesearch.jsp ]- 5! "+delySataList);
				
				req.setAttribute("count", count);
				req.setAttribute("paging", paging);
				req.setAttribute("delyStatList", delySataList);
				req.setAttribute("codeList", codeList);
				req.setAttribute("recvDTOList", list);
				forward(req, resp, "latesearch.jsp");
				log.debug("[testcontroller - latesearch.jsp ]- end!!");				
				
			// 미발송
			}else if(command.equalsIgnoreCase("recvdateDelay")){
				log.debug("[testcontroller - recvdateDelay ] 1 !!");	
				String RECV_DATE = req.getParameter("recv_date");
				log.debug("[testcontroller - recvdateDelay ] 2 !! "+RECV_DATE);	
				TLO_DELY_TRCE_RECV_IF oneTwo = calDao.findByDelayOneTwo(RECV_DATE);
				log.debug("[testcontroller - recvdateDelay ] 3 !! "+RECV_DATE);
				TLO_DELY_TRCE_RECV_IF twoThree = calDao.findByDelayTwoThree(RECV_DATE);
				log.debug("[testcontroller - recvdateDelay ] 4 !! "+RECV_DATE);
				TLO_DELY_TRCE_RECV_IF threeOver = calDao.findByDelayThreeOver(RECV_DATE);
				log.debug("[testcontroller - recvdateDelay ] 5 !!");
				
				log.debug("[testcontroller - recvdateDelay paging ]- start ");
				// paging 처리
				PagingBean paging = new PagingBean();
				if(req.getParameter("nowPage") == null){
					 paging.setNowPage(1);
				}else{
					 paging.setNowPage(Integer.valueOf(req.getParameter("nowPage")));
				}
				log.debug("[testcontroller - recvdateDelay paging ]- end ");
				
				req.setAttribute("paging", paging);
				req.setAttribute("oneTwo",oneTwo);
				req.setAttribute("twoThree",twoThree);
				req.setAttribute("threeOver",threeOver);
				forward(req, resp, "late_calc_result.jsp");
				log.debug("[testcontroller - recvdateDelay ] 3 !!");
			
			// 처음 검색메뉴 눌렀을때 나오는 메뉴
			}else if(command.equalsIgnoreCase("search")){
				log.debug("[controller - search_result.jsp ]- start!!");
		        SimpleDateFormat formatter1 = new SimpleDateFormat ("yyyy-MM-dd");
		        String date = formatter1.format(new Date());
		        
		        // 데이터 전체 카운트 
		        int count = dao.selectALLRecvDataCNT();
		        
				// paging 처리 - start 
				PagingBean paging = new PagingBean();
				if(req.getParameter("nowPage") == null){
					 paging.setNowPage(1);
				}else{
					 paging.setNowPage(Integer.valueOf(req.getParameter("nowPage")));
				}
				PagingUtil.setPagingInfo(paging);
				// paging 처리 - end
		        
				// limit로 가져오는 개수 처리하기 위한 변수
				int pgCount = paging.getNowPage()==1?1:paging.getNowPage()*paging.getCountPerPage();
				
		        // 처음 검색메뉴 눌렀을때 나오는 기본데이터 ( 현재시간 기준 1달전데이터 보여주기 )
				String str = String.format(" and RECV_DATE >= ('%s' - INTERVAL 1 MONTH) limit %d,%d ",date,pgCount,pgCount+paging.getCountPerPage());
				log.debug("[controller - search_result.jsp ]- 1! ");
				
				Vector<TLO_DELY_TRCE_RECV_IF> list = dao.selectALLRecvData(str, "all");
				Vector<Code> codeList = cDao.getCodeLists();
				Vector<Code> delySataList = delyDao.getCodeLists();
				
				log.debug("[controller - search_result.jsp ]- 4! "+delySataList);
				req.setAttribute("count", count);
				req.setAttribute("paging", paging);
				req.setAttribute("delyStatList", delySataList);
				req.setAttribute("codeList", codeList);
				req.setAttribute("recvDTOList", list);
				forward(req, resp, "search_result.jsp");
				log.debug("[controller - search_result.jsp ]- end!!");
				
			//excell filedown
			}else if(command.equalsIgnoreCase("filedown")){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String strDate = sdf.format(new Date());
				try {
					log.debug("[testcontroller - filedown ]- start!!");
					String str = " limit 100 ";
					log.debug("[testcontroller - filedown ]- 1");
					Vector<TLO_DELY_TRCE_RECV_IF> products = dao.selectALLRecvData(str, "file");
					log.debug("[testcontroller - filedown ]- 2");
					DownloadView downloadView = new DownloadView();
					log.debug("[testcontroller - filedown ]- 3");
					Map<String, Object> model = new HashMap();
					log.debug("[testcontroller - filedown ]- 4");
					model.put("fileName", "롯데홈쇼핑_"+strDate+".xls");
					model.put("products", products);
					log.debug("[testcontroller - filedown - data ]- 확인 - "+products);
					log.debug("[testcontroller - filedown ]- 5");
					downloadView.buildExcelDocument( model, downloadView.createWorkbook(), req, resp);
					log.debug("[testcontroller - filedown ]- end!! model: "+model);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			// 전일배송완료
			}else if (command.equalsIgnoreCase("bfcomp")){
				log.debug("[testcontroller - bfcomp ]- start ");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String strDate = sdf.format(new Date());
				Vector<TLO_DELY_TRCE_RECV_IF> bfcompList = dao.selectBeforeComplete("2014-11-10");
				
				log.debug("[testcontroller - bfcomp paging ]- start ");
				// paging 처리
				PagingBean paging = new PagingBean();
				if(req.getParameter("nowPage") == null){
					 paging.setNowPage(1);
				}else{
					 paging.setNowPage(Integer.valueOf(req.getParameter("nowPage")));
				}
				log.debug("[testcontroller - bfcomp paging ]- end ");
				
				req.setAttribute("paging", paging);
				req.setAttribute("bfcompList", bfcompList);
				Vector<Code> codeList = cDao.getCodeLists();
				Vector<Code> delySataList = delyDao.getCodeLists();
				req.setAttribute("delyStatList", delySataList);
				req.setAttribute("codeList", codeList);				
				forward(req, resp, "bfcomp.jsp");
				log.debug("[testcontroller - bfcomp ]- end ");
				
			// 전일배송출발
			}else if(command.equalsIgnoreCase("bfstart")){
				log.debug("[testcontroller - bfstart ]- start ");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String strDate = sdf.format(new Date());
				Vector<TLO_DELY_TRCE_RECV_IF> bfstartList = dao.selectBeforeStart("2014-11-10");
				
				log.debug("[testcontroller - bfstart paging ]- start ");
				// paging 처리
				PagingBean paging = new PagingBean();
				if(req.getParameter("nowPage") == null){
					 paging.setNowPage(1);
				}else{
					 paging.setNowPage(Integer.valueOf(req.getParameter("nowPage")));
				}
				log.debug("[testcontroller - bfstart paging ]- end ");
				
				req.setAttribute("paging", paging);
				req.setAttribute("bfstartList", bfstartList);
				Vector<Code> codeList = cDao.getCodeLists();
				Vector<Code> delySataList = delyDao.getCodeLists();
				req.setAttribute("delyStatList", delySataList);
				req.setAttribute("codeList", codeList);				
				forward(req, resp, "bfstart.jsp");
				log.debug("[testcontroller - bfstart ]- end ");
				
			// 당일배송완료
			}else if(command.equalsIgnoreCase("daycomp")){
				log.debug("[testcontroller - daycomp ]- start ");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String strDate = sdf.format(new Date());
				Vector<TLO_DELY_TRCE_RECV_IF> daycompList = dao.selectDayComplete("2014-11-10");
				
				log.debug("[testcontroller - daycomp paging ]- start ");
				// paging 처리
				PagingBean paging = new PagingBean();
				if(req.getParameter("nowPage") == null){
					 paging.setNowPage(1);
				}else{
					 paging.setNowPage(Integer.valueOf(req.getParameter("nowPage")));
				}
				log.debug("[testcontroller - daycomp paging ]- end ");
				
				req.setAttribute("paging", paging);
				req.setAttribute("daycompList", daycompList);
				Vector<Code> codeList = cDao.getCodeLists();
				Vector<Code> delySataList = delyDao.getCodeLists();
				req.setAttribute("delyStatList", delySataList);
				req.setAttribute("codeList", codeList);				
				forward(req, resp, "daycomp.jsp");
				log.debug("[testcontroller - daycomp ]- end ");
				
			// 당일배송출발
			}else if(command.equalsIgnoreCase("daystart")){
				log.debug("[testcontroller - daystart ]- start ");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String strDate = sdf.format(new Date());
				Vector<TLO_DELY_TRCE_RECV_IF> daystartList = dao.selectDayStart("2014-11-10");
				
				log.debug("[testcontroller - daystart paging ]- start ");
				// paging 처리
				PagingBean paging = new PagingBean();
				if(req.getParameter("nowPage") == null){
					 paging.setNowPage(1);
				}else{
					 paging.setNowPage(Integer.valueOf(req.getParameter("nowPage")));
				}
				log.debug("[testcontroller - daystart paging ]- end ");
				
				req.setAttribute("paging", paging);
				req.setAttribute("daystartList", daystartList);
				Vector<Code> codeList = cDao.getCodeLists();
				Vector<Code> delySataList = delyDao.getCodeLists();
				req.setAttribute("delyStatList", delySataList);
				req.setAttribute("codeList", codeList);				
				forward(req, resp, "daystart.jsp");
				log.debug("[testcontroller - daystart ]- end ");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		log.debug("[testcontroller]- end !!");
	}
}
